import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:easy_video/internal/api/swiper_api.dart';
import 'package:easy_video/internal/api/video_api.dart';
import 'package:easy_video/model/video_category_model.dart';
import 'package:easy_video/model/video_model.dart';

import '../../model/swiper_model.dart';

class IndexController extends GetxController {
  List<SwiperModel> swiper_list = [];

  List<VideoCategoryModel> category_list = [];

  List<VideoModel> video_list = [];

  int current_category = 0;

  int video_list_current_page = 0;

  bool loadDone = false;

  TextEditingController searchInputController = TextEditingController();

  onInit() {
    super.onInit();
    this.resetGet();
  }

  resetGet() async {
    this.current_category = 0;
    this.video_list_current_page = 0;
    this.loadDone = false;
    this.swiper_list.clear();
    this.category_list.clear();
    this.video_list.clear();
    this.getSwiper();
    await this.getVideoCategory();
    this.getVideoIndex();
  }

  getSwiper() {
    SwiperApi().index().then((res) {
      for (var item in res.data["data"]) {
        this.swiper_list.add(SwiperModel.fromJson(item));
      }
      this.update();
    });
  }

  Future<void> getVideoCategory() async {
    var response = await VideoApi().category();
    for (var item in response.data["data"]) {
      this.category_list.add(VideoCategoryModel.fromJson(item));
    }
    this.update();
  }

  getVideoIndex() {
    if (this.loadDone) {
      return;
    }
    VideoCategoryModel currentCategory =
        this.category_list[this.current_category];
    VideoApi()
        .index(
      categoryId: currentCategory.Id,
      page: this.video_list_current_page,
    )
        .then((response) {
      for (var item in response.data["data"]["data"]) {
        this.video_list.add(VideoModel.fromJson(item));
      }
      if (response.data["data"]["last_page"] > this.video_list_current_page) {
        this.video_list_current_page++;
      } else {
        this.loadDone = true;
      }
      this.update();
    });
  }

  changeVideoCategory(int index) {
    this.current_category = index;
    this.video_list.clear();
    this.video_list_current_page = 0;
    this.loadDone = false;
    this.getVideoIndex();
  }
}
